//
//  HEFindServerMenuView.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/11/2.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEFindServerMenuView.h"
#import "HEGoodsMenuModel.h"
#import "HEFilterBottomView.h"
#import "HEMenuItemCell.h"
#import "TableViewHeaderView.h"
#import "HEMenuPriceRangeCell.h"

static NSString *const KCellItemId = @"HEMenuItemCell";
static NSString *const KCellPriceId = @"HEMenuPriceRangeCell";

@interface HEFindServerMenuView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray <HEGoodsMenuModel *> *titleModels;
@property (nonatomic, strong) NSMutableArray <QMUIButton *> *btnArr;
@property (nonatomic, assign) BOOL showInWindow;             //下拉列表展示在window上，以应对列表视图展示的问题（默认NO）
@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, assign) CGFloat maxHeight;
@property (nonatomic, assign) CGFloat inWindowMinY;
@property (nonatomic, assign) BOOL isShow;//是否展开

@property (nonatomic, strong) GDTableView *otherTableView;
@property (nonatomic, strong) GDTableView *leftTableView;
@property (nonatomic, strong) GDTableView *rightTableView;

@property (nonatomic, strong) HEFilterBottomView *bottomView;
@property (nonatomic, assign) NSInteger selectedTabIndex;
@property (nonatomic, strong) UIView *moreView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) HEDeptIndexPath *deptIndexPath;

@end

@implementation HEFindServerMenuView

- (instancetype)initWithFrame:(CGRect)frame maxHeight:(CGFloat)maxHeight menuType:(HEFilterMenuType)type {
    _menuType = type;
    return [self initWithFrame:frame maxHeight:maxHeight];
}

- (instancetype)initWithFrame:(CGRect)frame maxHeight:(CGFloat)maxHeight{
    if (self=[super initWithFrame:frame]) {
        
        self.backgroundColor = KWhiteColor;
        self.qmui_borderPosition = QMUIViewBorderPositionBottom;
        self.qmui_borderWidth = 0.5;
        self.qmui_borderColor = CSplitLineColor;
        self.inWindowMinY = 0;
        self.maxHeight = maxHeight;
        
        self.selectedTabIndex = -1;
        
        self.brandArr = @[].mutableCopy;
        
        self.sections = @[@"产品服务", @"价格区间"].mutableCopy;
        
        [self initUI];
    }
    return self;
}

- (void)initUI {
    NSArray *titleArr = @[@"排序",@"筛选"];
    NSArray *imageArr = @[@"down_arrow",@"selection_normal"];
    if (_menuType == HEFilterMenuTypeFindTeam) {
        titleArr = @[@"科室"];
        imageArr = @[@"down_arrow"];
    }

    _titleModels = @[].mutableCopy;
    _btnArr = @[].mutableCopy;
    
    for (int i = 0; i < titleArr.count; i++) {
        QMUIButton *btn = [[QMUIButton alloc] init];
        btn.imagePosition = QMUIButtonImagePositionRight;// 将图片位置改为在文字下方
        btn.tintColorAdjustsTitleAndImage = UIColor.blackColor;
        btn.adjustsImageTintColorAutomatically = NO;
        btn.spacingBetweenImageAndTitle = 10;
        [btn setImage:UIImageMake(imageArr[i]) forState:UIControlStateNormal];
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        btn.titleLabel.font = DYFont(15);
        [self addSubview:btn];
        btn.tag = i;
        [btn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        HEGoodsMenuModel *model = [HEGoodsMenuModel new];
        model.isDesc = YES;
        model.index = i;
        model.titleType = i == 0 ? HEFilterMenuDownTypeOnlyList: HEFilterMenuDownTypeOther;
        [_titleModels addObject:model];

        [_btnArr addObject:btn];
    }
    
    if (titleArr.count == 1) {
        [_btnArr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@0);
            make.right.equalTo(self).offset(-15);
            make.left.equalTo(self).offset(15);
            make.height.equalTo(@50);
        }];
    } else {
        [_btnArr mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@0);
            make.height.equalTo(@50);
        }];
        [_btnArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    }
}

- (void)titleClick:(UIButton *)sender {
    NSInteger tag = sender.tag;
    
    HEGoodsMenuModel *model = _titleModels[tag];
    
    // 控制视图列表数据
    if (tag == 0) {
        self.dataSource = _ratiosList;
    }else {
//        self.dataSource = _ratiosList;
    }
    
    // 控制视图列表显示
    if (self.selectedTabIndex == tag) {
        [self animateMenuViewWithShow:NO];
    }else {
        self.selectedTabIndex = tag;
        [self animateMenuViewWithShow:YES];
    }
    
    // 控制标题栏按钮显示
    if (tag != 1) {
        [self changeMenuTitleImageStatus:model.index];
    }else {
        [self resetTitleStatus];
    }
    
    if (tag == 0) {
    }
    
}

// 重置标题按钮状态
- (void)resetTitleStatus {
    
    if (_btnArr.count == 1) {
        for (int i = 0 ; i < _btnArr.count; i++) {
            QMUIButton *btn = _btnArr[i];
            HEGoodsMenuModel *model = _titleModels[i];
            model.isDesc = YES;
            [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [btn setImage:UIImageMake(@"down_arrow") forState:UIControlStateNormal];
        }
    }else {
        for (int i = 0 ; i < _btnArr.count - 1; i++) {
            QMUIButton *btn = _btnArr[i];
            HEGoodsMenuModel *model = _titleModels[i];
            model.isDesc = YES;
            [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [btn setImage:UIImageMake(@"down_arrow") forState:UIControlStateNormal];
        }
    }
}

- (void)changeMenuTitleImageStatus:(NSInteger)index {
    QMUIButton *btn = _btnArr[index];
    HEGoodsMenuModel *model = _titleModels[index];
    
    // 重置标题按钮状态
    [self resetTitleStatus];

    model.isDesc = !model.isDesc;
    if (model.isDesc) {
        [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [btn setImage:UIImageMake(@"down_arrow") forState:UIControlStateNormal];
    }else {
        [btn setTitleColor:CNavBgColor forState:UIControlStateNormal];
        [btn setImage:UIImageMake(@"up_arrow") forState:UIControlStateNormal];
    }
}


/** 筛选视图显示&关闭 */
- (void)animateMenuViewWithShow:(BOOL)show {
    CGRect menuViewFrom = self.frame;
    UIView *superView = self.superview;
    CGFloat moreWidth = menuViewFrom.size.width;
    CGFloat leftTabWidth = menuViewFrom.size.width / 2.0;
    
//    if (self.selectedTabIndex == 0) {
//        _rightTableView.hidden = NO;
//        leftTabWidth = menuViewFrom.size.width / 2.0;
//    }else if (self.selectedTabIndex == 1){
//        _rightTableView.hidden = YES;
//        leftTabWidth = menuViewFrom.size.width;
//    }
    _rightTableView.hidden = YES;
    leftTabWidth = menuViewFrom.size.width;

    CGFloat viewHeight = 310;
 
    HEGoodsMenuModel *model = _titleModels[self.selectedTabIndex];
    
    if (self.showInWindow) {
        menuViewFrom.origin = CGPointMake(menuViewFrom.origin.x, self.inWindowMinY);
        superView = kApplication.keyWindow;
    }
    
    if (show) {
        self.backGroundView.frame = CGRectMake(0, CGRectGetMaxY(menuViewFrom), menuViewFrom.size.width, self.maxHeight);
        [self.superview bringSubviewToFront:self];
        [superView addSubview:self.backGroundView];
        self.bottomView.hidden = NO;

        if (model.titleType == HEFilterMenuDownTypeOther) {
            self.moreView.frame = CGRectMake(menuViewFrom.origin.x, CGRectGetMaxY(menuViewFrom), moreWidth, 0);
            [superView addSubview:self.moreView];
            
            [self.leftTableView removeFromSuperview];
            [self.rightTableView removeFromSuperview];
        }
        else if (model.titleType == HEFilterMenuDownTypeOnlyList) {
            self.leftTableView.frame = CGRectMake(menuViewFrom.origin.x, CGRectGetMaxY(menuViewFrom), leftTabWidth, 0);
            self.rightTableView.frame = CGRectMake(leftTabWidth, CGRectGetMaxY(menuViewFrom), leftTabWidth, 0);

            [superView addSubview:self.leftTableView];
            [superView addSubview:self.rightTableView];
            [self.moreView removeFromSuperview];
        }
        
        [UIView animateWithDuration:0.3 animations:^{
            self.backGroundView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.3f];

            if (model.titleType == HEFilterMenuDownTypeOther) {
                self.moreView.frame = CGRectMake(menuViewFrom.origin.x, CGRectGetMaxY(menuViewFrom), moreWidth, viewHeight);
                [self.otherTableView reloadData];
            }
            else if (model.titleType == HEFilterMenuDownTypeOnlyList) {
                self.leftTableView.frame = CGRectMake(menuViewFrom.origin.x, CGRectGetMaxY(menuViewFrom), leftTabWidth, viewHeight);
                self.rightTableView.frame = CGRectMake(leftTabWidth, CGRectGetMaxY(menuViewFrom), leftTabWidth, viewHeight);

                [self.leftTableView reloadData];
                [self.rightTableView reloadData];
            }
        }];
        
    }else {
        [self resetTitleStatus];

        [UIView animateWithDuration:0.3 animations:^{
            self.backGroundView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.f];
            self.moreView.frame = CGRectMake(self.moreView.frame.origin.x, self.moreView.frame.origin.y, self.moreView.frame.size.width, 0);
            
            self.leftTableView.frame = CGRectMake(self.leftTableView.frame.origin.x, self.leftTableView.frame.origin.y, self.leftTableView.frame.size.width, 0);
            self.rightTableView.frame = CGRectMake(leftTabWidth, self.leftTableView.frame.origin.y, self.leftTableView.frame.size.width, 0);

            self.bottomView.hidden = YES;
        } completion:^(BOOL finished) {
            self.selectedTabIndex = -1;
            [self.backGroundView removeFromSuperview];
            [self.moreView removeFromSuperview];
            [self.leftTableView removeFromSuperview];
            [self.rightTableView removeFromSuperview];
        }];
    }
    self.isShow = show;
}

/** 点击背景恢复默认 */
- (void)backGroundViewTappedClick:(UITapGestureRecognizer *)tapGesture
{
    [self hideMenuList];
}

/** 隐藏 */
- (void)hideMenuList
{
    if (!_isShow) {
        return;
    }
    [self animateMenuViewWithShow:NO];
}

#pragma mark -

- (void)setBrandArr:(NSMutableArray<HEBrandModel *> *)brandArr {
    _brandArr = brandArr;
//    [self.otherTableView reloadData];
}

- (void)refreshList {
    [self.otherTableView reloadData];
}


- (void)resetListSelect:(NSArray *)dataSource {
    for (HEFindFiterModel *model in dataSource) {
        model.isChoose = NO;
    }
}

#pragma mark - UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _otherTableView) {
        return 2;
    }else if(tableView == _leftTableView) {
        return 1;
    }else if(tableView == _rightTableView) {
        return 1;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _otherTableView) {
        return 1;
    }else if(tableView == _leftTableView) {
        return self.dataSource.count;
    }else if(tableView == _rightTableView) {
        HEFindFiterModel *model = self.dataSource[self.deptIndexPath.currentLeftIndex];
        return model.children.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _otherTableView) {
        if (indexPath.section == 0) {
            HEMenuItemCell *cell = [tableView dequeueReusableCellWithIdentifier:KCellItemId];
            cell.brandArr = self.brandArr;
            return cell;
        }
        HEMenuPriceRangeCell *cell = [tableView dequeueReusableCellWithIdentifier:KCellPriceId];
        cell.model = _titleModels.lastObject;
        return cell;
    }else if(tableView == _leftTableView) {

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        HEFindFiterModel *model = self.dataSource[indexPath.row];
        cell.textLabel.text = model.name;
        
        if (model.isChoose) {
            cell.textLabel.textColor = CNavBgColor;
            cell.backgroundColor = [CNavBgColor colorWithAlphaComponent:0.1];
        }else {
            cell.textLabel.textColor = CNavLightBlackColor;
            cell.backgroundColor = KWhiteColor;
        }
        
        return cell;
    }else if(tableView == _rightTableView) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"rightCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"rightCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        HEFindFiterModel *hspModel = self.dataSource[self.deptIndexPath.currentLeftIndex];
        HEFindFiterModel *model = hspModel.children[indexPath.row];
        cell.textLabel.text = model.name;
        
        if (model.isChoose) {
            cell.textLabel.textColor = CNavBgColor;
            cell.backgroundColor = KHexColor(@"EAF1FD");
        }else {
            cell.textLabel.textColor = CNavLightBlackColor;
            cell.backgroundColor = KWhiteColor;
        }
        
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _otherTableView) {
        if (indexPath.section == 0) {
            CGFloat h = ceilf(self.brandArr.count / 3.0) * 40 + 30;
            return h;
        }else {
            return 60;
        }
    }
    
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == _leftTableView) {
        [self resetListSelect: self.dataSource];
        HEFindFiterModel *model = self.dataSource[indexPath.row];
        model.isChoose = YES;
        
        [_leftTableView reloadData];

        if (self.selectedTabIndex == 0) {
            // 记录当前选中左侧id
            self.deptIndexPath.currentLeftIndex = indexPath.row;
            
            if ([_delegate respondsToSelector:@selector(menuView:didSelectSortWithModel:)]) {
                [_delegate menuView:self didSelectSortWithModel:model];
            }
            QMUIButton *btn = _btnArr[self.selectedTabIndex];
            [btn setTitle:model.name forState:UIControlStateNormal];
            
            [self hideMenuList];
            
//            if ([model.name isEqualToString:@"全部"]) {
//                // 清空之前选中右侧的选项
//                HEFindFiterModel *lastModel = self.dataSource[self.deptIndexPath.selectLeftIndex];
//                [self resetListSelect: lastModel.children];
//
//                // 保存当前选中的数据id
//                self.deptIndexPath.selectRightIndex = indexPath.row;
//                self.deptIndexPath.selectLeftIndex = indexPath.row;
//
//                QMUIButton *btn = _btnArr[self.selectedTabIndex];
//                [btn setTitle:model.name forState:UIControlStateNormal];
//
//                if ([_delegate respondsToSelector:@selector(menuView:didSelectWithHospModel:deptModel:)]) {
//                    [_delegate menuView:self didSelectWithHospModel:model deptModel:model];
//                }
//
//                [self hideMenuList];
//
//                return;
//            }
//
//            [_rightTableView reloadData];
//            if (indexPath.row == self.deptIndexPath.selectLeftIndex) {
//                [_rightTableView scrollToRow:self.deptIndexPath.selectRightIndex inSection:0 atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
//            }
//        } else if (self.selectedTabIndex == 1) {
//            if ([_delegate respondsToSelector:@selector(menuView:didSelectSortWithModel:)]) {
//                [_delegate menuView:self didSelectSortWithModel:model];
//            }
//            QMUIButton *btn = _btnArr[self.selectedTabIndex];
//            [btn setTitle:model.name forState:UIControlStateNormal];
//
//            [self hideMenuList];
        }
    }else if(tableView == _rightTableView) {
        
        // 清空之前选中右侧的选项
        HEFindFiterModel *lastModel = self.dataSource[self.deptIndexPath.selectLeftIndex];
        [self resetListSelect: lastModel.children];
        
        // 保存当前选中的数据id
        self.deptIndexPath.selectRightIndex = indexPath.row;
        self.deptIndexPath.selectLeftIndex = self.deptIndexPath.currentLeftIndex;

        HEFindFiterModel *hspModel = self.dataSource[self.deptIndexPath.currentLeftIndex];
        HEFindFiterModel *model = hspModel.children[indexPath.row];
        model.isChoose = YES;
        [_rightTableView reloadData];
        
        if ([model.name isEqualToString:@"全部"]) {
            QMUIButton *btn = _btnArr[self.selectedTabIndex];
            [btn setTitle:hspModel.name forState:UIControlStateNormal];
        }else {
            QMUIButton *btn = _btnArr[self.selectedTabIndex];
            [btn setTitle:model.name forState:UIControlStateNormal];
        }
        
        if ([_delegate respondsToSelector:@selector(menuView:didSelectWithHospModel:deptModel:)]) {
            [_delegate menuView:self didSelectWithHospModel:hspModel deptModel:model];
        }
         
        [self hideMenuList];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _otherTableView) {
        return 45;
    }
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _otherTableView) {
        TableViewHeaderView *view = [[TableViewHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
        view.name.text = self.sections[section];
        return view;
    }
    return nil;
}

#pragma mark - lazyloading

- (HEDeptIndexPath *)deptIndexPath {
    if (!_deptIndexPath) {
        _deptIndexPath = [HEDeptIndexPath new];
    }
    return _deptIndexPath;
}

- (UITableView *)otherTableView {
    if (!_otherTableView) {
        _otherTableView = [[GDTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _otherTableView.rowHeight = KTableViewCellHeight;
        _otherTableView.dataSource = self;
        _otherTableView.delegate = self;
        _otherTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _otherTableView.tableFooterView = [[UIView alloc]init];
        _otherTableView.showsVerticalScrollIndicator = NO;
        _otherTableView.backgroundColor = KWhiteColor;
        
        [_otherTableView registerClass:[HEMenuItemCell class] forCellReuseIdentifier: KCellItemId];
        [_otherTableView registerClass:[HEMenuPriceRangeCell class] forCellReuseIdentifier: KCellPriceId];

    }
    return _otherTableView;
}

- (UITableView *)leftTableView {
    if (!_leftTableView) {
        _leftTableView = [[GDTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _leftTableView.rowHeight = KTableViewCellHeight;
        _leftTableView.dataSource = self;
        _leftTableView.delegate = self;
        _leftTableView.separatorColor = CSplitLineColor;
        _leftTableView.tableFooterView = [[UIView alloc]init];
        _leftTableView.showsVerticalScrollIndicator = YES;
        _leftTableView.backgroundColor = KWhiteColor;
    }
    return _leftTableView;
}

- (UITableView *)rightTableView
{
    if (!_rightTableView) {
        _rightTableView = [[GDTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _rightTableView.rowHeight = KTableViewCellHeight;
        _rightTableView.dataSource = self;
        _rightTableView.delegate = self;
        _rightTableView.separatorColor = KLineColor;
        _rightTableView.backgroundColor = KItemBGColor;
        _rightTableView.separatorInset = UIEdgeInsetsZero;
        _rightTableView.tableFooterView = [[UIView alloc]init];
        _rightTableView.showsVerticalScrollIndicator = NO;
    }
    return _rightTableView;
}

- (UIView *)backGroundView
{
    if (!_backGroundView) {
        _backGroundView = [[UIView alloc] init];
        _backGroundView.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.f];
        _backGroundView.opaque = NO;
        UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backGroundViewTappedClick:)];
        [_backGroundView addGestureRecognizer:gesture];
    }
    return _backGroundView;
}

- (HEFilterBottomView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[HEFilterBottomView alloc] initBottomViewWithTarget:self resetAction:@selector(resetAction) confirmAction:@selector(confirmAction)];
    }
    return _bottomView;
}

- (UIView *)moreView {
    if (!_moreView) {
        _moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0)];
        _moreView.clipsToBounds = YES;
        _moreView.backgroundColor = KWhiteColor;
        [self addSubview:_moreView];
        
        self.otherTableView.frame = CGRectMake(0, 0, KScreenWidth, 260);
        [_moreView addSubview:self.otherTableView];
        
        self.bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.otherTableView.frame), KScreenWidth, 50);
        [_moreView addSubview:self.bottomView];
    }
    return _moreView;
}

/** 确定 */
- (void)confirmAction {
    [self animateMenuViewWithShow:NO];
    
    HEGoodsMenuModel *model = _titleModels.lastObject;
    model.selectBrand = @[].mutableCopy;
    for (HEBrandModel *brand in self.brandArr) {
        if (brand.isSelect) {
            [model.selectBrand addObject: [NSString stringWithFormat:@"'%@'", brand.name]];
        }
    }

    if ([_delegate respondsToSelector:@selector(menuView:didSelectConfirmWithBradIds:minPrice:maxPrice:)]) {
        [_delegate menuView:self didSelectConfirmWithBradIds:[model.selectBrand componentsJoinedByString:@","] minPrice:model.minPrice maxPrice:model.maxPrice];
    }
}

/** 重置 */
- (void)resetAction {
    for (HEBrandModel *model in self.brandArr) {
        model.isSelect = NO;
    }
    HEGoodsMenuModel *model = _titleModels.lastObject;
    model.minPrice = NULL;
    model.maxPrice = NULL;
    [self.otherTableView reloadData];
}



@end

 
@implementation HEDeptIndexPath
@end
